<?php

namespace app\admin\controller;

use support\spark\model\system\ComImages;
use Intervention\Image\ImageManagerStatic as Image;
use support\exception\BusinessException;
use support\Request;
use Shopwwi\WebmanFilesystem\Facade\Storage;
class AttachmentController extends Curd
{


    public  function  upload(Request $request){
        $cateId = $request->input('cate_id', 0);
        $data = $this->base($request, '/upload/img/'.date('Ymd'));
        $realpath = $data['realpath'];
        try {
            $img = Image::make($realpath);
            $max_height = 1170;
            $max_width = 1170;
            $width = $img->width();
            $height = $img->height();
            $ratio = 1;
            if ($height > $max_height || $width > $max_width) {
                $ratio = $width > $height ? $max_width / $width : $max_height / $height;
            }
            $img->resize($width*$ratio, $height*$ratio)->save($realpath);
        } catch (\Exception $e) {
            unlink($realpath);
            return sparkSuccess( [
                'code'  => 500,
                'msg'  => '处理图片发生错误'
            ]);
        }
        // 存储入库
         ComImages::insertGetId([
            'cate_id' => $cateId,
            'name' => $data['name'],
            'sha1' => '',
            'url' => $data['url'],
            'path' => $data['realpath'],
            'ext' => $data['ext'],
            'folder' => 'img',
            'type' => 'local',
            'create_time' => date('Y-m-d H:i:s')
        ]);
        return sparkSuccess( [
            'code'  => 0,
            'msg'  => '上传成功',
            'data' => [
                'url' => $data['url'],
                'name' => $data['name'],
                'size' => $data['size'],
            ]
        ]);
    }

    protected function base(Request $request, $relative_dir): array
    {
        $relative_dir = ltrim($relative_dir, '/');
        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new BusinessException('未找到上传文件', 400);
        }

        $base_dir = base_path() . '/public/';
        $full_dir = $base_dir . $relative_dir;
        if (!is_dir($full_dir)) {
            mkdir($full_dir, 0777, true);
        }

        $ext = strtolower($file->getUploadExtension());
        $ext_forbidden_map = ['php', 'php3', 'php5', 'css', 'js', 'html', 'htm', 'asp', 'jsp'];
        if (in_array($ext, $ext_forbidden_map)) {
            throw new BusinessException('不支持该格式的文件上传', 400);
        }

        $relative_path = $relative_dir . '/' . bin2hex(pack('Nn',time(), random_int(1, 65535))) . ".$ext";
        $full_path = $base_dir . $relative_path;
        $file_size = $file->getSize();
        $file_name = $file->getUploadName();
        $mime_type = $file->getUploadMimeType();
        $file->move($full_path);
        $image_with = $image_height = 0;
        if ($img_info = getimagesize($full_path)) {
            [$image_with, $image_height] = $img_info;
            $mime_type = $img_info['mime'];
        }

        return [
            'url'     => "/$relative_path",
            'name'     => $file_name,
            'realpath' => $full_path,
            'size'     => $file_size,
            'mime_type' => $mime_type,
            'image_with' => $image_with,
            'image_height' => $image_height,
            'ext' => $ext,
        ];
    }

    /**
     * 上传其他资源
     */
    public function uploadOtherFile()
    {
        set_time_limit(0);
        $file = request()->file('file');
        // 上传到本地服务器
        try {
            // 存到本地
            $result = Storage::adapter('public')->path('storage/upload/txt')->size(1024*1024*5)->extYes(['text/plain'])->upload($file);
            return sparkSuccess(['code' => 0, 'data' => [
                'url' => $result->file_url,
                'name' => rtrim($result->origin_name)
            ], 'msg' => '上传成功']);
        } catch (\Exception $e) {
            return sparkSuccess(['code' => 500, 'data' => [], 'msg' => $e->getMessage()]);
        }

    }
}
